﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Linkmeme.Models;

namespace Linkmeme
{

    public interface ISourceProvider<TSource> where TSource : SourceBase
    {
        List<TSource> GetUserFeed(string username);
        List<TSource> GetFriendsFeed(string username);
        int ProviderId { get; set; }
    }

    public abstract class RssSourceProvider
    {
        ContentProvider _provider;
        private ContentProvider Provider
        {
            get
            {
                if (_provider == null)
                {
                    LinkmemeDataContext context = new LinkmemeDataContext();
                    _provider = context.ContentProviders.Where(cp => cp.ID == ProviderId).Select(cp => cp).Single();
                }
                return _provider;
            }
        }

        public int ProviderId { get; set; }
        public string ProviderUserName { get; set; }

        public string RssUrl
        {
            get
            {
                return string.Format(Provider.UrlTemplate, ProviderUserName);
            }
        }

        public string DisplayName
        {
            get
            {
                return Provider.DisplayName;
            }
        }

        
    }

    public class PhotoRssSourceProvider : RssSourceProvider, ISourceProvider<Picture>
    {
        #region ISourceProvider<TSource> Members

        public List<Picture> GetUserFeed(string username)
        {
            ProviderUserName = username;
            List<Picture> itemList = Linkmeme.Utility.FeedReader.GetPhoto(RssUrl, DisplayName);
            return itemList;
        }

        public List<Picture> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class BlogRssSourceProvider : RssSourceProvider, ISourceProvider<Blog>
    {

        #region ISourceProvider<TSource> Members

        public List<Blog> GetUserFeed(string username)
        {
            ProviderUserName = username;
            List<Blog> itemList = Linkmeme.Utility.FeedReader.GetBlog(RssUrl, DisplayName);
            return itemList;
        }

        public List<Blog> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class BookmarkRssSourceProvider : RssSourceProvider, ISourceProvider<Bookmark>
    {
        #region ISourceProvider<TSource> Members

        public List<Bookmark> GetUserFeed(string username)
        {
            ProviderUserName = username;
            List<Bookmark> itemList = Linkmeme.Utility.FeedReader.GetBookmark(RssUrl, DisplayName);
            return itemList;
        }

        public List<Bookmark> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    public class StatusRssSourceProvider : RssSourceProvider, ISourceProvider<Status>
    {
        #region ISourceProvider<TSource> Members

        public List<Status> GetUserFeed(string username)
        {
            ProviderUserName = username;
            List<Status> itemList = Linkmeme.Utility.FeedReader.GetStatus(RssUrl, DisplayName);
            return itemList;
        }

        public List<Status> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
    




    
    #region Provider Factory
    public class SourceProviderFactory<TSourceType> where TSourceType : SourceBase
    {
        public ISourceProvider<TSourceType> CreateRssSourceProvider(int providerId)
        {
            ISourceProvider<TSourceType> provider = null;
            string t = typeof(TSourceType).ToString();
            t = t.Substring(t.LastIndexOf(".")+1).ToLower();

            switch (t)
            {
                case "picture":
                    provider = (ISourceProvider<TSourceType>)new PhotoRssSourceProvider() { ProviderId = providerId};
                    break;
                case "blog":
                    provider = (ISourceProvider<TSourceType>)new BlogRssSourceProvider() { ProviderId = providerId };
                    break;
                case "bookmark":
                    provider = (ISourceProvider<TSourceType>)new BookmarkRssSourceProvider() { ProviderId = providerId };
                    break;
                case "status":
                    provider = (ISourceProvider<TSourceType>)new StatusRssSourceProvider() { ProviderId = providerId };
                    break;
                default:
                    break;
            }
            return provider;
        }

        /* Old Provider Factory
        public ISourceProvider<TSourceType> CreateSourceProvider(int providerId)
        {
            ISourceProvider<TSourceType> provider = null; ;
            string providerName = GetProviderName(providerId);

            switch (typeof(TSourceType).ToString())
            {
                case "Linkmeme.Picture":

                    switch (providerName)
                    {
                        case "yupoo":
                            provider = (ISourceProvider<TSourceType>)new YupooProvider();
                            break;
                        case "flickr":
                            provider = (ISourceProvider<TSourceType>)new FlickrProvider();
                            break;
                        default:
                            break;
                    }

                    break;


                case "Linkmeme.Bookmark":

                    switch (providerName)
                    {
                        case "del.icio.us":
                            provider = (ISourceProvider<TSourceType>)new DeliciousProvider();
                            break;
                        case "googlebookmark":
                            provider = (ISourceProvider<TSourceType>)new GoogleBookmarkProvider();
                            break;
                        default:
                            break;
                    }

                    break;


                case "Linkmeme.Blog":

                    switch (providerName)
                    {
                        case "baiduspace":
                            provider = (ISourceProvider<TSourceType>)new BaiduSpaceProvider();
                            break;
                        case "livespace":
                            provider = (ISourceProvider<TSourceType>)new LiveSpaceProvider();
                            break;
                        default:
                            break;
                    }

                    break;

                default:
                    break;
            }

           


            return provider;
        }


        private static string GetProviderName(int providerId)
        {
            LinkmemeDataContext context = new LinkmemeDataContext();
            string provname = context.ContentProviders.Where(cp => cp.ID == providerId).Select(cp => cp.Name.ToLower()).Single();
            return provname;
        }
        */
    }
    #endregion
    

    /* Old Providers Implementation

    #region Photo Providers
    class YupooProvider : ISourceProvider<Picture>      //from my designed yahoo pipes
    {
        #region ISourceProvider<Picture> Members


        public int ProviderId { get; set; }

        List<Picture> ISourceProvider<Picture>.GetUserFeed(string username)
        {
           

            string rssUrl = string.Format("http://pipes.yahoo.com/pipes/pipe.run?_id=lHlhMxH63BGcGZvd2R2EvQ&_render=rss&username={0}", username);   //"bbpnb"
            XNamespace media = "http://search.yahoo.com/mrss/";
            XDocument doc = XDocument.Load(rssUrl);

            List<Picture> imgList = (from img in doc.Descendants("item")
                                     let content = img.Element(media + "thumbnail")
                                     let pubdate = FormatDateTimeStr(img.Element("pubDate").Value)  //" PDT", PST and so on
                                     select new Picture
                                     {
                                         ProviderName = "又拍",
                                         UserName = ExtractUserName(img.Element("author").Value),
                                         Link = img.Element("link").Value,
                                         PubDate = DateTime.Parse(pubdate), //DateTime.Parse(img.Element("pubDate").Value),
                                         Url = content.Attribute("url").Value,
                                         Type = img.Element(media + "category").Value, //content.Attribute("type").Value,
                                         Width = int.Parse(content.Attribute("width").Value),
                                         Height = int.Parse(content.Attribute("height").Value)
                                     }).ToList<Picture>();
           

            return imgList;
        }

        List<Picture> ISourceProvider<Picture>.GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }


        private string ExtractUserName(string author)
        {
            try
            {
                Regex re = new System.Text.RegularExpressions.Regex(".*\\((.*)\\)");
                Match m = re.Match(author);
                return m.Groups[1].Value;

            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        private string FormatDateTimeStr(string dt)
        {
            return dt.Substring(0, dt.LastIndexOf(" ")).Trim();
        }
        #endregion
    }

    class FlickrProvider : ISourceProvider<Picture>
    {

        #region ISourceProvider<Picture> Members
        public int ProviderId { get; set; }

        public List<Picture> GetUserFeed(string username)
        {

            string rssUrl = string.Format("http://pipes.yahoo.com/pipes/pipe.run?_id=e503773a5c163d71436ae48ed0c09a60&_render=rss&username={0}", "bbpnb");
            XNamespace media = "http://search.yahoo.com/mrss/";
            XDocument doc = XDocument.Load(rssUrl);

            List<Picture> imgList = (from img in doc.Descendants("item")
                                     //let content = img.Element(media + "thumbnail")
                                     //let pubdate = img.Element("pubDate").Value.Replace(" PDT", "")
                                     select new Picture
                                     {
                                         ProviderName = "flckr",
                                         UserName = img.Element("author").Value,
                                         Link = img.Element("link").Value,
                                         PubDate = DateTime.Now.AddDays(-10), //DateTime.Parse(pubdate), //DateTime.Parse(img.Element("pubDate").Value),
                                         Url = GetPhotoAddress(img.Element("description").Value), //content.Attribute("url").Value,
                                         Type = "test", //img.Element(media + "category").Value, //content.Attribute("type").Value,
                                         Width = 50,   //int.Parse(content.Attribute("width").Value),
                                         Height = 50   //int.Parse(content.Attribute("height").Value)
                                     }).ToList<Picture>();

            return imgList;
        }

        public List<Picture> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        
        #endregion

        private string GetPhotoAddress(string desc)
        {
            Regex re = new Regex(".*(http://farm.*\\.jpg)");
            Match m = re.Match(desc);
            return m.Groups[1].Value;
        }
    }
    #endregion
    

    #region Blog Providers

    class BaiduSpaceProvider : ISourceProvider<Blog>      //from my designed yahoo pipes
    {
        #region ISourceProvider<Picture> Members
        public int ProviderId { get; set; }
        List<Blog> ISourceProvider<Blog>.GetUserFeed(string username)
        {
            

            string rssUrl = string.Format("http://hi.baidu.com/{0}/rss", username);   //"lookuptable", "guanwei"

            List<Blog> blogList = Linkmeme.Utility.FeedReader.GetBlog(rssUrl, "百度空间");

            return blogList;
        }

        List<Blog> ISourceProvider<Blog>.GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }


        #endregion
    }

    class LiveSpaceProvider : ISourceProvider<Blog>      //from my designed yahoo pipes
    {
        #region ISourceProvider<Picture> Members
        public int ProviderId { get; set; }
        List<Blog> ISourceProvider<Blog>.GetUserFeed(string username)
        {


            string rssUrl = string.Format("http://{0}.spaces.live.com/feed.rss", username);   //"bbpnb"

            List<Blog> blogList = Linkmeme.Utility.FeedReader.GetBlog(rssUrl, "Live Space");

            return blogList;
        }

        List<Blog> ISourceProvider<Blog>.GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }


        #endregion
    }

    #endregion
    

    #region Bookmark Provider

    class DeliciousProvider : ISourceProvider<Bookmark>
    {

        #region ISourceProvider<Bookmark> Members
        public int ProviderId { get; set; }
        public List<Bookmark> GetUserFeed(string username)
        {
            string rssUrl = string.Format("http://feeds.delicious.com/rss/{0}", username);   //bbpnb
            List<Bookmark> bookmarkList = Linkmeme.Utility.FeedReader.GetBookmark(rssUrl, username);
            return bookmarkList;
        }

        public List<Bookmark> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    class GoogleBookmarkProvider : ISourceProvider<Bookmark>
    {

        #region ISourceProvider<Bookmark> Members
        public int ProviderId { get; set; }
        public List<Bookmark> GetUserFeed(string username)
        {
            throw new NotImplementedException();
        }

        public List<Bookmark> GetFriendsFeed(string username)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
    #endregion
     * */
}
